/**
 * 用户增删改查相关的model
 */

import { message } from 'antd';
import * as update from 'immutability-helper'
// 工具类
import { strEnum, settings, Logger } from '../utils';
// service调用
import { userQuery } from '../services';
// typescript 定义
import { Model } from 'dva';
import { Dispatch } from 'redux';
import { History, Location } from 'history';
// logger
const logger = Logger.get('models_user');
/**
 * 命名空间: user
 */
export const namespace = 'user';

/**
 * Action枚举: user
 */
export const Action = strEnum([
  'query',
  'querySuccess',
  'queryFailure',
]);

/**
 * 用户数据的interface
 */
export interface User {
  id: number;
  userId: string,
  name: string
}

/**
 * 用户Model的State接口
 */
export interface State {
  list: Array<User>,
  total: number
}

/**
 * 用户State的初始数据
 */
const state: State = {
  list: [],
  total: 0
}

/**
 * 用户的Model
 */
const user: Model = {
  /**
   * 命名空间
   */
  namespace,
  /**
   * store状态
   */
  state,
  /**
   * 订阅事件
   */
  subscriptions: {
    /**
     * 订阅url跳转时的处理
     * @param param0
     */
    setup({ dispatch, history }: { dispatch: Dispatch<any>, history: History}) {
      // 判断是否为服务器端渲染
      if(!settings.isServer) {
        // 客户端渲染时启用监听
        return history.listen((location: Location): void => {
          if(location.pathname === '/user') {
            // 跳转到/user的时候，进行画面数据加载
            dispatch({
              type: Action.query
            });
          }
        });
      }
    }
  },
  /**
   * 异步action处理
   */
  effects: {
    /**
     * 查询用户列表
     * @param param0
     * @param param1
     */
    *[Action.query] ({ payload }: any, { call, put, select }): Generator {
      logger.info('query');
      // 调用查询
      const result = yield call(userQuery);
      logger.log(result);
      const { success, data, total, message } = result;
      if (success && data) {
        // 成功获得用户列表
        yield put({
          type: Action.querySuccess,
          payload: {
            list: data,
            total: total
          }
        });
      } else {
        // 错误处理
        yield put({
          type: Action.queryFailure,
          payload: message
        });
      }
    }
  },
  /**
   * 同步action处理
   */
  reducers: {
    /**
     * 查询成功
     * @param state
     * @param param1
     */
    [Action.querySuccess] (state: State, { payload: { list, total } }:
          { payload: { list:Array<User>, total: number } }): State {
      logger.info('querySuccess');
      logger.log(list);
      logger.log(total);
      return update(state, {
        list: {
          $set: list
        },
        total: {
          $set: total
        }
      });
    },
    /**
     * 查询失败
     * @param state
     * @param param1
     */
    [Action.queryFailure] (state: State, { payload }: { payload: string}): State {
      //显示错误信息
      logger.info('queryFailure');
      logger.log(payload);
      message.error(payload);
      return state;
    }
  }
}

export default user;
